package com.alianzamedica.servlets.filters;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.alianzamedica.businessobject.Doctor;
import com.alianzamedica.models.ProfileModel;

/**
 * @author Carlos
 * 
 */
public class PermissionFilter implements Filter {

	@Override
	public void destroy() {
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse resp,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) resp;
		HttpSession session = request.getSession();
		String requestedURI = request.getRequestURI().toString();
		String context = request.getContextPath();
		requestedURI = requestedURI.substring(context.length());

		System.out.println("requestedURI: " + requestedURI);
		ProfileModel model = new ProfileModel();
		try {

			if (model.urlExists(requestedURI)) {
				Doctor doctor = (Doctor) session.getAttribute("doctor");
				if (model.userIsLoggingIn(requestedURI)) {
					chain.doFilter(request, response);
				} else if (doctor == null) {
					RequestDispatcher dispatcher = request
							.getRequestDispatcher("/invalidAccess.do");
					dispatcher.forward(request, response);
				} else {
					if (model.hasAccess(doctor, requestedURI)) {
						chain.doFilter(request, response);
					} else {
						RequestDispatcher dispatcher = request
								.getRequestDispatcher("/noAccess.do");
						dispatcher.forward(request, response);
					}
				}
			} else {
				chain.doFilter(request, response);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

}
